package cn.itsource.controller;

import cn.itsource.domain.ArticleType;
import cn.itsource.query.Query;
import cn.itsource.service.ArticleTypeService;
import cn.itsource.util.AjaxResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/articleType")
public class ArticleTypeController {

    @Autowired
    private ArticleTypeService articleTypeService;

    //注意前端地址：http://localhost:8080/articleType - get
    @GetMapping
    public List<ArticleType> findAll() {
        return articleTypeService.findAll();
    }


    //注意前端地址：http://localhost:8080/articleType/1 - get
    @GetMapping("/{id}")
    public ArticleType findOne(@PathVariable("id") Long id) {
        return articleTypeService.findOne(id);
    }


   //注意前端地址：http://localhost:8080/articleType - put - {}
   @PutMapping
   public AjaxResult addorUpdate(@RequestBody ArticleType articleType){
       try {
           if(articleType.getId()==null){//添加操作
               articleTypeService.add(articleType);
           }else{
               articleTypeService.update(articleType);
           }
           //如果成功
           return new AjaxResult();
       } catch (Exception e) {
           e.printStackTrace();
           return new AjaxResult(false,"网络繁忙,请稍后重试");
       }
   }

    //注意前端地址：http://localhost:8080/articleType/1 - delete
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id")Long id){
        try {
            articleTypeService.delete(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"网络繁忙,请稍后重试");
        }
    }
    //分页+模糊查询
   @PostMapping
   public PageInfo<ArticleType> pageQuery(@RequestBody Query query){

        //前端接收参数：total，list
        return articleTypeService.pageQuery(query);
   }

    //批量删除
   @PatchMapping
   public AjaxResult patchdel(@RequestBody Long[] ids){
       try {
           articleTypeService.patchdel(ids);
           return new AjaxResult();
       } catch (Exception e) {
           e.printStackTrace();
           return new AjaxResult(false,"网络繁忙,请稍后重试");
       }
   }

}
